layui.define(
    [
        "layer",
        "element",
        "laydate",
        "laypage",
        "laytpl",
        "table",
        "form",
        "upload"
    ],
    function (exports) {
        var layer = layui.layer,
            element = layui.element,
            $ = layui.$;

        var obj = {
            index: function () {
                //收起侧边栏
                $("#LAY_app_flexible").click(function () {
                    obj.treeNav();
                });
                $(".layadmin-body-shade").click(function () {
                    if ($("#LAY_app_flexible").hasClass("layui-icon-shrink-right")) {
                        $("#LAY_app_flexible").removeClass("layui-icon-shrink-right").addClass("layui-icon-spread-left");
                    } else {
                        $("#LAY_app_flexible").removeClass("layui-icon-spread-left").addClass("layui-icon-shrink-right");
                    }
                    $("#LAY_app").removeClass("layadmin-side-spread-sm");
                });
                //侧边栏收起,tips提示
                $(".layui-nav a").mouseenter(function () {
                    if ($(this).attr("tips") != undefined && $("#LAY_app").hasClass("layadmin-side-shrink")) {
                        layer.tips($(this).attr("tips"), $(this), {
                            time: 99999
                        });
                    }
                }).mouseleave(function () {
                    layer.closeAll("tips");
                });
                //导航,打开选项卡
                $(".layui-nav-tree a").click(function () {
                    var _url = $(this).attr("url");
                    var _name = $(this).attr("name");
                    var _id = $(this).attr("id") || _url;
                    obj.openNav(_url, _name, _id);
                    if ($("#LAY_app").hasClass("layadmin-side-shrink")) obj.treeNav();
                });
                //导航选项卡切换
                element.tab({
                    headerElem: '#LAY_app_tabsheader>li',
                    bodyElem: '#LAY_app_body>.layadmin-tabsbody-item'
                });
                element.on('tab(layout-tabs)', function (data) {
                    var _layid = $(this).attr('lay-id');
                    var _l = 0;
                    var _w = $(".layui-tab-title").width();
                    $(".layui-tab-title li").each(function (index, item) {
                        if (data.index >= index) {
                            var _p = 31;
                            if (index > 0) _p = 56;
                            _l += $(item).width() + _p;
                        }
                    });
                    $(".layui-tab-title").scrollLeft(_l - _w);

                    //展开对应侧导航
                    $(".layui-nav-tree .layui-nav-itemed").removeClass('layui-nav-itemed');
                    $(".layui-nav-tree .layui-this").removeClass('layui-this');
                    $(".layui-nav-tree a[id=" + _layid + "]").parents('li').addClass('layui-nav-itemed');
                    $(".layui-nav-tree a[id=" + _layid + "]").parent().addClass('layui-this');
                });
                //监听关闭选项卡
                element.on('tabDelete(layout-tabs)', function (data) {
                    var _item = $(".layadmin-tabsbody-item").eq(data.index);
                    if (_item.next().length) {
                        _item.next().addClass("layui-show");
                    } else {
                        _item.prev().addClass("layui-show");
                    }
                    _item.remove();
                });

                $("#closeThisTabs").click(function () {
                    var _this = $(".layui-tab-title .layui-this");
                    var _index = _this.index();
                    var _id = _this.attr("lay-id");
                    if (_index == 0) return;
                    element.tabDelete('layout-tabs', _id);
                });
                $("#closeOtherTabs").click(function () {
                    $(".layui-tab-title li").each(function (index, item) {
                        if (index > 0 && $(item).attr('lay-id')) {
                            if ($(item).hasClass('layui-this') == false) element.tabDelete('layout-tabs', $(item).attr('lay-id'));
                        }
                    });
                });
                $("#closeAllTabs").click(function () {
                    $(".layui-tab-title li").each(function (index, item) {
                        if (index > 0 && $(item).attr('lay-id')) {
                            element.tabDelete('layout-tabs', $(item).attr('lay-id'));
                        }
                    });
                });
                $("#refreshThisTabs").click(function () {
                    var _this = $("#LAY_app_body .layui-show iframe");
                    _this.attr('src', _this.attr('src'));
                });


                $("#leftPage").click(function () {
                    obj.leftNav();
                });
                $("#rightPage").click(function () {
                    obj.rightNav();
                });

            },
            treeNav: function () {
                //侧导航收展
                var _class = "layadmin-side-shrink";
                if ($(window).width() > 768) {
                    _class = "layadmin-side-shrink";
                } else {
                    _class = "layadmin-side-spread-sm";
                }
                if ($("#LAY_app_flexible").hasClass("layui-icon-shrink-right")) {
                    $("#LAY_app_flexible").removeClass("layui-icon-shrink-right").addClass("layui-icon-spread-left");
                    $("#LAY_app").addClass(_class);
                } else {
                    $("#LAY_app_flexible").removeClass("layui-icon-spread-left").addClass("layui-icon-shrink-right");
                    $("#LAY_app").removeClass(_class);
                }
            },
            openNav: function (_url, _name, _id) {
                if (window.location.href != top.window.location.href) {
                    var _i = top.layui.$("#LAY_app_tabsheader").find("li[lay-id='" + _id + "']").index();
                    if (_url != undefined && _i == -1) {
                        top.layui.$("#LAY_app_body").append(['<div class="layadmin-tabsbody-item layui-show">', '<iframe src="' + _url + '" frameborder="0" class="layadmin-iframe"></iframe>', "</div>"].join(""));
                        top.layui.element.tabAdd('layout-tabs', {
                            title: "<span>" + _name + "</span>",
                            id: _id
                        });
                        top.layui.$("#LAY_app_body .layui-show").eq(0).removeClass("layui-show");
                        top.layui.element.tabChange('layout-tabs', _id);
                    } else if (_url != undefined && _i > -1) {
                        top.layui.$("#LAY_app_body .layadmin-tabsbody-item").eq(_i).find('iframe').attr('src', top.layui.$("#LAY_app_body .layadmin-tabsbody-item").eq(_i).find('iframe').attr('src'));
                        top.layui.$("#LAY_app_body .layadmin-tabsbody-item").eq(_i).addClass("layui-show").siblings().removeClass("layui-show");
                        top.layui.element.tabChange('layout-tabs', _id);
                    }
                } else {
                    var _i = $("#LAY_app_tabsheader").find("li[lay-id='" + _id + "']").index();
                    if (_url != undefined && _i == -1) {
                        $("#LAY_app_body").append(['<div class="layadmin-tabsbody-item layui-show">', '<iframe src="' + _url + '" frameborder="0" class="layadmin-iframe"></iframe>', "</div>"].join(""));
                        element.tabAdd('layout-tabs', {
                            title: "<span>" + _name + "</span>",
                            id: _id
                        });
                        $("#LAY_app_body .layui-show").eq(0).removeClass("layui-show");
                        element.tabChange('layout-tabs', _id);
                    } else if (_url != undefined && _i > -1) {
                        $("#LAY_app_body .layadmin-tabsbody-item").eq(_i).find('iframe').attr('src', $("#LAY_app_body .layadmin-tabsbody-item").eq(_i).find('iframe').attr('src'));
                        $("#LAY_app_body .layadmin-tabsbody-item").eq(_i).addClass("layui-show").siblings().removeClass("layui-show");
                        element.tabChange('layout-tabs', _id);
                    }
                }
            },
            leftNav: function () {
                var _w = $(".layui-tab-title").width();
                var _sl = parseInt($(".layui-tab-title").scrollLeft());
                var _left = _sl - _w / 2;
                $(".layui-tab-title").scrollLeft(_left);
            },
            rightNav: function () {
                var _w = $(".layui-tab-title").width();
                var _sl = parseInt($(".layui-tab-title").scrollLeft());
                var _left = _sl + _w / 2;
                $(".layui-tab-title").scrollLeft(_left);
            },
            open: function (_url, _title) {   //弹出打开
                if (_title == undefined) _title = "新窗口";
                layer.open({
                    type: 2,
                    title: _title,
                    content: _url,
                    maxmin: true,
                    moveOut: true,
                    area: ['90%', '90%']

                })
            },
            post: function (_data, _close, _url) {
                //CKEditor 赋值
                for (_i in CKEDITOR.instances) {
                    _data[_i] = CKEDITOR.instances[_i].getData();
                }

                var _load = layer.load(2);
                if (_url == undefined) _url = window.location.href;
                $.ajax({
                    url: _url,
                    type: 'POST',
                    dataType: 'json',
                    data: _data,
                })
                    .done(function (_json) {
                        if (_json.code == 1) {
                            if (_close == 1) {
                                top.layer.msg(_json.msg);
                                parent.window.location.reload();
                            } else {
                                layer.msg(_json.msg, function () {
                                    if (_json.url) {
                                        window.location.href = _json.url;
                                    } else {
                                        window.location.reload();
                                    }
                                });
                            }
                        } else {
                            layer.alert(_json.msg, {icon: 5});
                        }
                    })
                    .fail(function () {
                        layer.msg('出问题了,请联系管理员');
                    })
                    .always(function () {
                        layer.close(_load);
                    });
            },
            page_config: {
                limit: 20,
                limits: [20, 50, 100]
            }
        };

        $("body").on("click",".open",function () {
            var _url = $(this).attr('url');
            var _title = $(this).attr('title') == undefined ? $(this).text() : $(this).attr('title');
            if (_url != undefined) obj.open(_url, _title);
        });

        $("body").on("click",".openNav",function () {
            var _id = $(this).attr('id') == undefined ? Math.random() : $(this).attr('id');
            var _url = $(this).attr('url');
            var _title = $(this).attr('title') == undefined ? $(this).text() : $(this).attr('title');
            if (_url != undefined) obj.openNav(_url, _title, _id);
        });

        //up-input有图片就显示
        $(document).on("mouseenter", ".up-input.image,.cos-up-input.image", function () {
            if ($(this).val() != "") {
                layer.open({
                    type: 1,
                    title: false,
                    closeBtn: 0,
                    area: '300px',
                    offset: 'rt',
                    skin: 'layui-layer-nobg', //没有背景色
                    shade: false,
                    content: '<div style="padding: 10px;background: #FFF;"><img src="' + $(this).val() + '" width="100%" /></div>'
                });
            }
        }).on("mouseleave", ".up-input.image,.cos-up-input.image", function () {
            layer.close(layer.index);
        });

        //图片上传
        if ($(".up-btn").length) {
            var upload = layui.upload;
            upload.render({
                elem: '.up-btn'
                , acceptMime: 'image/*'
                , url: CONFIG.upImgUrl //上传接口
                , before: function (obj) {
                    layer.load(2);
                }
                , done: function (res) {
                    if (res.code == 1) {
                        layer.msg(res.msg);
                        $(this.item).parents(".layui-form-item").find('.up-input').val(res.src);
                    } else {
                        layer.alert(res.msg);
                    }
                    layer.closeAll('loading');
                }
                , error: function () {
                    layer.closeAll('loading');
                    layer.alert('出了点小问题,请联系管理员');
                }
            });
        }

        //CKeditor编辑器
        $(".ckeditors").each(function () {
            CKEDITOR.replace($(this).attr('name'), CONFIG.ckeditor);
        });

        //COS图片上传
        $(".cos-up-btn").each(function () {
            var _this = $(this);
            var _path = _this.attr('path') || '';
            var _fileInput = $('<input class="layui-upload-file" type="file" accept="' + ($(this).attr('accept') || "*") + '">').change(function () {
                var file = this.files[0];
                if (!file) return;
                // 分片上传文件
                cos.sliceUploadFile({
                    Bucket: Bucket,
                    Region: Region,
                    Key: _path + (new Date()).getTime() + '_' + file.name,
                    Body: file,
                    onHashProgress: function (progressData) {
                        // console.log('校验中', JSON.stringify(progressData));
                    },
                    onProgress: function (progressData) {
                        if(progressData.percent==0) layer.load(2,{shade:0.3});
                        if(progressData.percent==1){
                            layer.closeAll();
                            $(_fileInput).val('');
                        }
                        // console.log('上传中', JSON.stringify(progressData));
                    },
                }, function (err, data) {
                    if (err == null) {
                        _this.parents(".layui-form-item").find('.cos-up-input').val('https://' + data.Location);
                    } else {
                        layer.alert('COS配置错误');
                    }
                });
            });
            $(this).after(_fileInput);
        }).click(function () {
            $(this).siblings("input[type='file']").click();
        });

        exports("app", obj);
    }
);
